<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-item label="文件上传" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <!--<DtgUploadFile :fileList="fileList" :showUploadList="true" @changeFile="handleChange"></DtgUploadFile>-->

              <template v-if="isAdd">
                <a-upload
                  :action="uploadAction"
                  :multiple="false"
                  :headers="tokenHeader"
                  :data="{biz:bizPath}"
                  :file-list="fileList"
                  :before-upload="beforeUpload"
                  @change="handleChange"
                >
                  <a-button> <a-icon type="upload" /> 文件上传 </a-button>
                </a-upload>
              </template>
              <template v-else>{{fileName}}</template>

            </a-form-item>
          </a-col>
          <!--<a-col :span="24">
            <a-form-item label="创建人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['createBy']" placeholder="请输入创建人"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="创建日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择创建日期" v-decorator="['createTime']" :trigger-change="true" style="width: 100%"/>
            </a-form-item>
          </a-col>-->
          <a-col :span="24">
            <a-form-item label="密级" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <!--<a-input-number v-decorator="['secretLev']" placeholder="请输入密级" style="width: 100%"/>-->
              <a-select default-value="非密" @change="handleSelChange">
                <a-select-option :value="item.name" v-for="(item,i) in selList" :key="i">
                  {{item.name}}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!--<a-col :span="24">
            <a-form-item label="编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['fileCode']" placeholder="请输入编号"></a-input>
            </a-form-item>
          </a-col>-->
          <!--<a-col :span="24">
            <a-form-item label="文件名" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['fileTitle', validatorRules.fileTitle]" placeholder="请输入文件名"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="编制单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['orgBelong']" placeholder="请输入编制单位"></a-input>
            </a-form-item>
          </a-col>-->
          <a-col :span="24">
            <a-form-item label="文件描述" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['fileDescription']" placeholder="请输入文件描述"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="所属装备" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input style="width: 427px; margin-right: 10px" v-decorator="['eqpBelong']" placeholder="请输入所属装备"></a-input>
              <a-button type="primary" @click="addEquipment">选择</a-button>
            </a-form-item>
          </a-col>
          <!--<a-col :span="24">
            <a-form-item label="文件路径" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['filePath', validatorRules.filePath]" placeholder="请输入文件路径"></a-input>
            </a-form-item>
          </a-col>-->
          <!--<a-col :span="24">
            <a-form-item label="文档大小(B)" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-decorator="['fileSize']" placeholder="请输入文档大小(B)" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="文档格式" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['fileTypes']" placeholder="请输入文档格式"></a-input>
            </a-form-item>
          </a-col>-->

          <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col>
        </a-row>

        <EquipmentMmodal ref="equipmentTable"
                         :tableData="tableData"
                         :selectedFileRowKeys="selectedFileRowKeys"
                         :tableType="'radio'"
                         @equipmentOk="handleEquipmentOk"
                         @equipmentChange="equipmentChange">
        </EquipmentMmodal>

      </a-form>
    </j-form-container>
  </a-spin>
</template>

<script>
  import Vue from 'vue'
  import { ACCESS_TOKEN } from "@/store/mutation-types"
  import { httpAction, getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import JDate from '@/components/jeecg/JDate'
  import DtgUploadFile from './DtgUploadFile'
  import EquipmentMmodal from './EquipmentMmodal'
  import { getEquipmentInfoList } from '@/api/digitization'


  export default {
    name: 'DtgFileDetailsInfoForm',
    components: {
      JFormContainer,
      JDate,
      DtgUploadFile,
      EquipmentMmodal
    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      /*这个属性用于控制文件上传的业务路径*/
      bizPath:{
        type:String,
        required:false,
        default:"temp"
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        form: this.$form.createForm(this),
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          fileTitle: {
            rules: [
              { required: true, message: '请输入文件名!'},
            ]
          },
          filePath: {
            rules: [
              { required: true, message: '请输入文件路径!'},
            ]
          },
        },
        url: {
          add: "/datamanage/fileTransManage/add",
          edit: "/datamanage/fileTransManage/edit",
          queryById: "/base/dtgFileDetailsInfo/queryById"
        },
        fileList:[],
        fileInfo:{},
        userInfo: this.$store.getters.userInfo,
        isAdd: true,
        tokenHeader: {'X-Access-Token': Vue.ls.get(ACCESS_TOKEN)},
        uploadAction:window._CONFIG['domianURL']+"/sys/common/upload",
        eqpBelong:'',
        selectedFileRowKeys: [],
        tableData: [],
        selList:[
          {
            value: 0,
            name: '非密'
          },
          {
            value: 1,
            name: '一般'
          },
          {
            value: 2,
            name: '秘密'
          },
          {
            value: 3,
            name: '绝密'
          },
        ],
        isChangeFile: false,
        fileName: '',
      }
    },
    computed: {
      formDisabled(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return true
          }
        }
        return false
      }
    },
    created () {
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
      this.initTableData();
    },
    methods: {
      handleSelChange(v){
        console.log(v);
      },
      initTableData(){
        getEquipmentInfoList().then(res => {
          this.tableData = res.result.records;
        })
      },
      addEquipment(){
        this.$refs['equipmentTable'].handleAddEquipment();
      },
      handleEquipmentOk(selData) {
        console.log(selData);
        if(selData.selectedFileList.length){
          this.model = {'eqpBelong': selData.selectedFileList[0].name};
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.model,'eqpBelong'))
            this.eqpBelong = selData.selectedFileList[0].id
          })
        }
      },
      equipmentChange(selData){
        this.selectedFileRowKeys = selData.selectedFileRowKeys;
      },
      beforeUpload(){
        this.fileList = [];
      },
      handleChange(info){
        // if(info.file.status == 'done'){
          let fileList = [...info.fileList];
          fileList = fileList.slice(-2);
          fileList = fileList.map(file => {
            if (file.response) {
              file.url = file.response.url;
            }
            return file;
          });
          this.fileList = fileList;
          this.fileInfo = info.file;
          this.isChangeFile = true;
        // }
        debugger
      },
      add () {
        this.edit({});
      },
      edit (record) {
        if(JSON.stringify(record) == '{}'){
          this.isAdd = true;
          this.fileList = [];
          this.selectedFileRowKeys = [];
        }else{
          this.fileList = [];
          this.isAdd = false;
          this.fileList = [{
              uid: record.id,
              name: record.fileTitle,
              status: 'done',
              url: record.filePath,
          }]
        }
        this.fileName = record.fileTitle;

        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'secretLev','fileDescription','eqpBelong'))
        })

      },
      //渲染流程表单数据
      showFlowData(){
        if(this.formBpm === true){
          let params = {id:this.formData.dataId};
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.edit (res.result);
            }
          });
        }
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let formData = Object.assign(this.model, values);
            let {username,createBy,createTime,updateBy,updateTime,orgCode} = this.userInfo;

            console.log("表单提交数据",formData)
            console.log(that.fileInfo)

            if(JSON.stringify(that.fileInfo) == '{}' && !formData.id){
              that.$message.warning('请上传文件')
              that.confirmLoading = false;
              return false;
            }

            let fileType = '';
            let fileTitle = '';
            let filePath = '';
            let fileMixName = '';
            let fileCode = '';

            if(that.isAdd || that.isChangeFile){
              let info = that.fileInfo;
              fileType = info.name.split('.')[1]
              fileTitle = info.name;
              filePath = info.response.message;
              fileMixName = filePath.split('/')[1];
              fileCode = info.uid;
            }

            let params = {};
            let obj = {};
            let obb = {};

            obb = {
              id:'',
              createBy:username,
              createTime,
              updateBy,
              updateTime,
              sysOrgCode:orgCode,
              fileCode,
              fileTitle,
              eqpBelong: values.eqpBelong,
              filePath,
              fileMixName,
              fileTypes: fileType,
              fileSize:  that.fileInfo.size ? that.fileInfo.size : '',
              pid: that.eqpBelong,
              modelName:'新增文件',
              eqpUid: that.eqpBelong
            };
            obb = Object.assign({},obb,formData);

            obj = {
              id: '',
              createBy:username,
              createTime,
              updateBy,
              updateTime,
              sysOrgCode:orgCode,
              versionNo:'1.0',
            };


            params = {
              obj,
              obb
            }

            httpAction(httpurl,params,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }

        })
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(this.model,'secretLev','fileDescription','eqpBelong'))
      },
    }
  }
</script>